<template>
  <div class="audio-box" :class="{ active: isActive }" @click="audioClick">
    <div class="audio-top">
      <p class="audio-title">{{title}}</p>
      <p class="audio-time">{{timeFormat}}</p>
    </div>
    <div class="audio-content">{{content}}</div>
    <div style="display: none;">
      <audio :src="url" ref="audioObj"
             @play="audioPlay" @pause="audioPause" @timeupdate="audioProgress"></audio>
    </div>
    <div class="audio-progress" :style="{ width: progress + 'px'}"></div>
  </div>
</template>

<style lang="less">
  @import './audio.less';
</style>

<script>
  import reqwest from 'reqwest'
  import jsBase64 from 'js-base64'
  import eventBus from 'byted-toutiao-pc-business-components/src/js/eventBus.js'
  import { durationFormat } from 'byted-toutiao-pc-business-components/src/js/utils'
  const Base64 = jsBase64.Base64

  export default {
    name: 'TtAudio',
    props: {
      id: String,
      title: String,
      time: String,
      content: String
    },
    data () {
      return {
        url: '',
        isActive: false,
        progress: 0
      }
    },
    mounted () {
      eventBus.$on('tt-audio-play', (id) => {
        if (this.id !== id && this.isActive) {
          this.$refs.audioObj.pause()
        }
      })
    },
    computed: {
      timeFormat () {
        return durationFormat(this.time)
      }
    },
    methods: {
      audioClick () {
        if (!this.isActive) {
          if (this.url === '') {
            this._getAudioUrl()
          } else {
            // 再次播放
            if (this.progress === this.containerWidth) {
              this.$refs.audioObj.currentTime = 0
              this.progress = 0
            }
            this.$refs.audioObj.play()
          }
        } else {
          this.$refs.audioObj.pause()
        }
      },
      audioPlay () {
        eventBus.$emit('tt-audio-play', this.id)
        this.isActive = true
      },
      audioPause () {
        this.isActive = false
      },
      audioProgress (e) {
        if (!this.containerWidth) this.containerWidth = this.$el.clientWidth
        let cur = this.$refs.audioObj.currentTime
        let p = cur / this.time
        p = p > 1 ? 1 : p
        this.progress = p * this.containerWidth
      },
      _getAudioUrl () {
        // 获取真正的播放地址
        reqwest({
          method: 'GET',
          type: 'jsonp',
          url: '//i.snssdk.com/audio/urls/1/toutiao/mp4/' + this.id,
          success: (res) => {
            if (res.message === 'success') {
              this.url = Base64.decode(res.data.audio_list.audio_1.main_url.replace(/\n/gi, ''))
              this.$nextTick(() => {
                this.$refs.audioObj.play()
              })
            }
          },
          error: () => {
          }
        })
      }
    }
  }
</script>



// WEBPACK FOOTER //
// audio.vue?1fdb64c6
